$(document).ready(function () {
	$("#console").hide();

	var display = function (text) {
	    $("#console_center").hide();
	    $("#console").hide();
	    $("#console").html(text);
	    $("#console").fadeIn();
	};

	var display_c = function (text) {
	    $("#console").hide();
	    $("#console_center").hide();
	    $("#console_center").html(text);
	    $("#console_center").fadeIn();
	};

	var get_server_name = function (num) {
	    var	servers = {
		1:	"Jiva",
		2:	"Rushu",
		3:	"Djaul",
		4:	"Raval",
		5:	"Hecate",
		6:	"Sumens",
		7:	"Menalt",
		8:	"Rosal",
		9:	"Maimane",
		10:	"Silvosse",
		11:	"Brumaire",
		12:	"Pouchechot",
		13:	"Silouate",
		14:	"Domen",
		15:	"Amayiro",
		16:	"Rykke-Errel",
		17:	"Hyrkul",
		18:	"Helsephine",
		19:	"Allister",
		20:	"Otomai",
		21:	"Lily",
		23:	"Hel Munster",
		24:	"Danathor",
		25:	"Kuri",
		26:	"Mylaise",
		27:	"Goultard",
		28:	"Ulette",
		29:	"Vil Smiss",
		30:	"Many",
		31:	"Solar",
		1001:	"Shika",
		3001:	"Nehra",
		4001:	"Alma",
		4002:	"Aguabrial",
		4003:	"Buhorado",
		4004:	"Tenebres",
		6001:	"Spiritia",
		7001:	"Dark Vlad",
		9001:	"Ereziah"
	    };
	    return servers[num] || "Unknown?";
	};

	var bind_players = function () {
	    $("li:not(.binded)").each(function () {
		    var that = this;

		    $(that).addClass("binded");
		    $(that).click(function () {
			    var json = $(that).data("json");
			    // Here we call our image generator
			    display("Creation de l'image en cours...");
			    $.post("create_image.php", json, function (data) {
				    var disp = "<img src=\"" + data.image + "\" alt=\"perso\" />";
				    disp += "<h2>Lien permanent</h2>";
				    disp += "<div class=\"permalink\">";
				    disp += "<a href=\"" + data.link + "\">" + data.link + "</a>"; 
				    disp += "</div>";
				    disp += "<p class=\"little\">" + "Ce lien est permanent, si votre perso change de niveau, l'image sera automatiquement mise a jour dans un delai de 24h." + "</p>";
				    display_c(disp);
				}, "json");
			});
		});
	};

	var search = function () {
	    if ((to_search = $("#search").attr("value")))
		{
		    display_c("Recherche en cours, cela peut prendre quelques secondes...");
		    $.post("search.php", {na: to_search}, function (data) {
			    var elem = document.createElement("ol");

			    for (var i in data)
				{
				    var li = document.createElement("li");
				    var str = "<a href=\"#\">" + data[i].na + "</a>" + " - level " + data[i].le + " (serveur " + get_server_name(data[i].hs) + ")";

				    $(li).append(str).data("json", data[i]).addClass("player");
				    $(elem).append(li);
				}
			    if (i)
				{
				    display(elem);
				    bind_players();
				}
			    else
				display_c("Pas de personnage trouve...");
			}, "json");
		}
	    else
		display_c("Veuillez preciser votre recherche...");
	};

	$("#search_form").submit(function () {
		search();
		return false;
	    });

	$("#search_icon").click(function () {
		search();
		return false;
	    });
    })
